package com.spark.tags;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

import com.spark.core.SparkContext;
import com.spark.core.XMap;

import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModelException;

@SuppressWarnings("unchecked")
public abstract class SparkTag {
	
	public void init(XMap view, SparkContext context) throws Exception {};
	
	public abstract String execute(XMap view, SparkContext context) throws Exception;
	
	
	protected String build(SparkContext context, String templateName) throws IOException, TemplateException{
		//是否启用模板
		//TODO:增加模板中变量的默认值，否则启用模板后出错
//		templateName = null;
		if(templateName != null) {
			StringWriter out = null;
			try {
				Template template = context.getFreemarkerConfiguration().getTemplate(templateName);
				out = new StringWriter();
				Map map = context.getMap();
				template.process(map, out);
				out.flush();
				return out.toString();//builder.toString();
			} catch(FileNotFoundException e){
				return build(context);			
			} finally {
				if (out != null)
					out.close();
			}
		}else {
			return build(context);
		}
	}
	
	protected String build( SparkContext context) throws TemplateModelException{
		return "";
	}
	
	@SuppressWarnings("unchecked")
	protected Object getObject(Map map ,String key, Object defaultValue){
		Object value = (Object)map.get(key);
		return (value == null) ? defaultValue : value;
	}
	
	@SuppressWarnings("unchecked")
	protected Object get(Map map ,String key){
		return getObject(map,key,"");
	}
}
